// 增强版用户管理系统 - JavaScript逻辑
// 文件路径: frontend/static/js/user_management_enhanced.js
// 功能说明: 支持高级过滤、批量操作、现代化UI交互的用户管理系统

class UserManagement {
  constructor() {
    this.users = [];
    this.filteredUsers = [];
    this.selectedUsers = new Set();
    this.roles = [];
    this.currentPage = 1;
    this.pageSize = 10;
    this.totalPages = 1;
    this.isLoading = false;
    
    this.init();
  }

  init() {
    console.log('UserManagement initializing...');
    this.bindEvents();
    this.loadRoles();
    this.loadUsers();
    console.log('UserManagement initialized');
  }

  bindEvents() {
    console.log('Binding events...');
    
    // 安全绑定事件 - 检查元素是否存在
    const bindEvent = (id, event, handler) => {
      const element = document.getElementById(id);
      if (element) {
        element.addEventListener(event, handler);
        console.log(`Bound ${event} to ${id}`);
      } else {
        console.warn(`Element ${id} not found for event binding`);
      }
    };
    
    // 筛选事件 - 使用正确的元素ID
    bindEvent('userTypeFilter', 'change', () => this.applyFilters());
    bindEvent('roleFilter', 'change', () => this.applyFilters());
    bindEvent('statusFilter', 'change', () => this.applyFilters());
    bindEvent('filterBindStatus', 'change', () => this.applyFilters());
    bindEvent('filterDateFrom', 'change', () => this.applyFilters());
    bindEvent('filterDateTo', 'change', () => this.applyFilters());
    bindEvent('quickSearch', 'input', this.debounce(() => this.applyFilters(), 300));
    bindEvent('applyFiltersBtn', 'click', () => this.applyFilters());
    bindEvent('searchBtn', 'click', () => this.applyFilters());
    
    // 重置筛选
    bindEvent('resetFiltersBtn', 'click', () => this.resetFilters());
    
    // 刷新数据
    bindEvent('refreshUsersBtn', 'click', () => this.loadUsers());
    
    // 批量操作
    bindEvent('selectAllUsers', 'change', (e) => this.toggleSelectAll(e.target.checked));
    bindEvent('batchDeleteBtn', 'click', () => this.batchDelete());
    bindEvent('batchRoleBtn', 'click', () => this.showBatchRoleModal());
    bindEvent('batchStatusBtn', 'click', () => this.showBatchStatusModal());
    
    // 创建用户
    bindEvent('createUserBtn', 'click', () => this.showCreateUserModal());
    
    // 表单提交
    bindEvent('userFormElement', 'submit', (e) => this.handleFormSubmit(e));
    
    // 表单取消
    bindEvent('userFormCancelBtn', 'click', () => this.hideUserFormModal());
    bindEvent('userFormCloseBtn', 'click', () => this.hideUserFormModal());
    
    // 批量操作确认
    bindEvent('confirmBatchRoleBtn', 'click', () => this.confirmBatchRoleAssignment());
    bindEvent('confirmBatchStatusBtn', 'click', () => this.confirmBatchStatusChange());
    
    // 分页
    bindEvent('prevPageBtn', 'click', () => this.changePage(this.currentPage - 1));
    bindEvent('nextPageBtn', 'click', () => this.changePage(this.currentPage + 1));
    bindEvent('pageSizeSelect', 'change', (e) => this.changePageSize(parseInt(e.target.value)));
    
    console.log('Events bound completed');
  }

  debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  }

  async loadRoles() {
    try {
      const response = await this.apiRequest('/api/admin/roles');
      if (response.success) {
        this.roles = response.data;
        this.renderRoleOptions();
      }
    } catch (error) {
      console.error('加载角色失败:', error);
      this.showMessage('加载角色失败', 'error');
    }
  }

  async loadUsers() {
    if (this.isLoading) return;
    
    console.log('Loading users...');
    this.isLoading = true;
    this.showLoadingState(true);
    
    try {
      // 检查是否有访问令牌
      const token = localStorage.getItem('access_token');
      if (!token) {
        throw new Error('未找到访问令牌，请重新登录');
      }
      
      const response = await this.apiRequest('/api/users');
      console.log('Users API response:', response);
      
      if (response.success) {
        this.users = response.data || [];
        console.log(`Loaded ${this.users.length} users:`, this.users);
        this.applyFilters();
        this.showMessage(`成功加载 ${this.users.length} 个用户`, 'success');
      } else {
        throw new Error(response.message || '加载用户失败');
      }
    } catch (error) {
      console.error('加载用户失败:', error);
      this.showMessage('加载用户失败: ' + error.message, 'error');
      
      // 如果是认证错误，提示登录
      if (error.message.includes('401') || error.message.includes('token')) {
        this.showLoginPrompt();
      }
    } finally {
      this.isLoading = false;
      this.showLoadingState(false);
    }
  }

  showLoginPrompt() {
    const userList = document.getElementById('userList');
    if (userList) {
      userList.innerHTML = `
        <tr>
          <td colspan="8" class="text-center py-4">
            <div class="alert alert-warning">
              <i class="bi bi-exclamation-triangle me-2"></i>
              请先<a href="/login" class="btn btn-sm btn-primary ms-2">登录</a>后查看用户列表
            </div>
          </td>
        </tr>
      `;
    }
  }

  /**
   * 应用用户筛选条件
   * 根据用户类型、角色、状态、日期范围和搜索关键词筛选用户
   */
  applyFilters() {
    // 安全获取筛选条件，避免null引用错误
    const userTypeEl = document.getElementById('userTypeFilter');
    const roleEl = document.getElementById('roleFilter');
    const statusEl = document.getElementById('statusFilter');
    const bindStatusEl = document.getElementById('filterBindStatus');
    const searchEl = document.getElementById('quickSearch');
    const dateFromEl = document.getElementById('filterDateFrom');
    const dateToEl = document.getElementById('filterDateTo');
    
    const userType = userTypeEl ? userTypeEl.value : '';
    const role = roleEl ? roleEl.value : '';
    const status = statusEl ? statusEl.value : '';
    const bindStatus = bindStatusEl ? bindStatusEl.value : '';
    const searchTerm = searchEl ? searchEl.value.toLowerCase() : '';
    const dateFrom = dateFromEl ? dateFromEl.value : '';
    const dateTo = dateToEl ? dateToEl.value : '';
    
    this.filteredUsers = this.users.filter(user => {
      // 用户类型筛选
      if (userType && user.user_type !== userType) return false;
      
      // 角色筛选
      if (role && !user.roles?.includes(role)) return false;
      
      // 状态筛选
      if (status && user.status !== status) return false;
      
      // 绑定状态筛选
      if (bindStatus) {
        if (bindStatus === 'bound' && !this.isUserBound(user)) return false;
        if (bindStatus === 'unbound' && this.isUserBound(user)) return false;
      }
      
      // 日期范围筛选
      if (dateFrom || dateTo) {
        const userDate = new Date(user.created_at);
        if (dateFrom && userDate < new Date(dateFrom)) return false;
        if (dateTo && userDate > new Date(dateTo + 'T23:59:59')) return false;
      }
      
      // 快速搜索
      if (searchTerm) {
        const searchFields = [
          user.username,
          user.real_name,
          user.mobile,
          user.email,
          user.department,
          user.position
        ].filter(Boolean).join(' ').toLowerCase();
        
        if (!searchFields.includes(searchTerm)) return false;
      }
      
      return true;
    });
    
    this.currentPage = 1;
    this.updatePagination();
    this.renderUsers();
    this.updateFilterSummary();
  }

  /**
   * 重置所有筛选条件
   * 将筛选表单恢复到初始状态并重新加载用户列表
   */
  resetFilters() {
    // 重置筛选表单
    const resetElement = (id) => {
      const el = document.getElementById(id);
      if (el) {
        if (el.type === 'select-one') {
          el.selectedIndex = 0;
        } else {
          el.value = '';
        }
      }
    };

    resetElement('userTypeFilter');
    resetElement('roleFilter');
    resetElement('statusFilter');
    resetElement('filterBindStatus');
    resetElement('quickSearch');
    resetElement('filterDateFrom');
    resetElement('filterDateTo');

    // 重新应用筛选（实际上是显示所有用户）
    this.applyFilters();
  }

  /**
   * 更新筛选结果统计信息
   */
  updateFilterSummary() {
    const countEl = document.getElementById('filterResultsCount');
    if (countEl) {
      countEl.textContent = `共 ${this.filteredUsers.length} 条记录`;
    }
  }

  checkDateRange(dateStr, range) {
    if (!dateStr || !range) return true;
    
    const date = new Date(dateStr);
    const now = new Date();
    
    switch (range) {
      case 'today':
        return date.toDateString() === now.toDateString();
      case 'week':
        const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        return date >= weekAgo;
      case 'month':
        const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
        return date >= monthAgo;
      case 'quarter':
        const quarterAgo = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
        return date >= quarterAgo;
      default:
        return true;
    }
  }

  resetFilters() {
    document.getElementById('userTypeFilter').value = '';
    document.getElementById('roleFilter').value = '';
    document.getElementById('statusFilter').value = '';
    document.getElementById('dateRangeFilter').value = '';
    document.getElementById('quickSearch').value = '';
    this.applyFilters();
  }

  updatePagination() {
    this.totalPages = Math.max(1, Math.ceil(this.filteredUsers.length / this.pageSize));
    if (this.currentPage > this.totalPages) {
      this.currentPage = this.totalPages;
    }
    
    const prevBtn = document.getElementById('prevPageBtn');
    const nextBtn = document.getElementById('nextPageBtn');
    const pageInfo = document.getElementById('pageInfo');
    
    prevBtn.disabled = this.currentPage <= 1;
    nextBtn.disabled = this.currentPage >= this.totalPages;
    
    const startItem = (this.currentPage - 1) * this.pageSize + 1;
    const endItem = Math.min(this.currentPage * this.pageSize, this.filteredUsers.length);
    pageInfo.textContent = `第 ${startItem}-${endItem} 项，共 ${this.filteredUsers.length} 项`;
  }

  renderUsers() {
    const container = document.getElementById('userCardsContainer');
    const tableContainer = document.getElementById('userTableContainer');
    const userList = document.getElementById('userList');
    
    const startIndex = (this.currentPage - 1) * this.pageSize;
    const endIndex = startIndex + this.pageSize;
    const pageUsers = this.filteredUsers.slice(startIndex, endIndex);
    
    if (pageUsers.length === 0) {
      if (userList) {
        userList.innerHTML = `
          <tr>
            <td colspan="8" class="text-center text-muted py-4">
              <i class="bi bi-info-circle me-2"></i>
              ${this.filteredUsers.length === 0 ? '暂无用户数据' : '当前页面无数据'}
            </td>
          </tr>
        `;
      }
      return;
    }
    
    // 使用表格布局（兼容现有模板）
    if (userList) {
      userList.innerHTML = pageUsers.map(user => this.renderUserTableRow(user)).join('');
    }
    
    this.updateSelectAllState();
  }

  renderUserTableRow(user) {
    const isSelected = this.selectedUsers.has(user.id);
    const statusClass = this.getStatusBadgeClass(user.status);
    const userTypeLabel = user.user_type === 'miniprogram' ? '小程序' : 'PC端';
    const roles = Array.isArray(user.roles) ? user.roles.join(', ') : (user.role || '');
    
    return `
      <tr class="user-row ${isSelected ? 'table-primary' : ''}">
        <td>
          <input class="form-check-input user-checkbox" type="checkbox" 
                 value="${user.id}" ${isSelected ? 'checked' : ''}>
        </td>
        <td>
          <div class="d-flex align-items-center">
            <i class="bi bi-person-circle me-2 text-muted"></i>
            <div>
              <strong>${user.username || ''}</strong>
              ${user.real_name ? `<br><small class="text-muted">${user.real_name}</small>` : ''}
            </div>
          </div>
        </td>
        <td>
          <span class="badge ${user.user_type === 'miniprogram' ? 'bg-info' : 'bg-secondary'}">
            ${userTypeLabel}
          </span>
        </td>
        <td>
          <div style="max-width: 120px; overflow: hidden; text-overflow: ellipsis;">
            ${roles || '-'}
          </div>
        </td>
        <td>
          <span class="badge ${statusClass}">${this.getStatusLabel(user.status)}</span>
        </td>
        <td>
          <span class="badge ${this.getBindStatusClass(user)}">
            ${this.getBindStatusLabel(user)}
          </span>
        </td>
        <td>
          <small class="text-muted">
            ${user.created_at ? new Date(user.created_at).toLocaleDateString() : '-'}
          </small>
        </td>
        <td>
          <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-primary" onclick="userManagement.editUser(${user.id})" 
                    title="编辑用户">
              <i class="bi bi-pencil"></i>
            </button>
            <button class="btn btn-outline-info" onclick="userManagement.viewUserDetail(${user.id})" 
                    title="查看详情">
              <i class="bi bi-eye"></i>
            </button>
            <button class="btn btn-outline-danger" onclick="userManagement.deleteUser(${user.id})" 
                    title="删除用户">
              <i class="bi bi-trash"></i>
            </button>
          </div>
        </td>
      </tr>
    `;
  }

  renderUserCard(user) {
    const isSelected = this.selectedUsers.has(user.id);
    const statusClass = this.getStatusClass(user.status);
    const userTypeLabel = user.user_type === 'miniprogram' ? '小程序' : 'PC端';
    const roles = Array.isArray(user.roles) ? user.roles.join(', ') : (user.role || '');
    
    return `
      <div class="col-md-6 col-lg-4">
        <div class="card user-card ${isSelected ? 'selected' : ''}">
          <div class="card-header d-flex justify-content-between align-items-center">
            <div class="form-check">
              <input class="form-check-input user-checkbox" type="checkbox" 
                     value="${user.id}" ${isSelected ? 'checked' : ''}>
            </div>
            <span class="badge ${statusClass}">${this.getStatusLabel(user.status)}</span>
          </div>
          <div class="card-body">
            <h6 class="card-title">
              <i class="bi bi-person-circle me-2"></i>
              ${user.username || ''}
            </h6>
            ${user.real_name ? `<p class="text-muted mb-1"><i class="bi bi-person me-2"></i>${user.real_name}</p>` : ''}
            ${user.mobile ? `<p class="text-muted mb-1"><i class="bi bi-telephone me-2"></i>${user.mobile}</p>` : ''}
            ${user.email ? `<p class="text-muted mb-1"><i class="bi bi-envelope me-2"></i>${user.email}</p>` : ''}
            ${user.department ? `<p class="text-muted mb-1"><i class="bi bi-building me-2"></i>${user.department}</p>` : ''}
            ${user.position ? `<p class="text-muted mb-1"><i class="bi bi-briefcase me-2"></i>${user.position}</p>` : ''}
            <p class="text-muted mb-1"><i class="bi bi-device-hdd me-2"></i>${userTypeLabel}</p>
            ${roles ? `<p class="text-muted mb-2"><i class="bi bi-shield-check me-2"></i>${roles}</p>` : ''}
            <small class="text-muted">创建时间: ${user.created_at ? new Date(user.created_at).toLocaleDateString() : ''}</small>
          </div>
          <div class="card-footer d-flex gap-1">
            <button class="btn btn-sm btn-outline-primary flex-fill" onclick="userManagement.editUser(${user.id})">
              <i class="bi bi-pencil"></i> 编辑
            </button>
            <button class="btn btn-sm btn-outline-info" onclick="userManagement.viewUserLog(${user.id})" title="查看日志">
              <i class="bi bi-clock-history"></i>
            </button>
            <button class="btn btn-sm btn-outline-danger" onclick="userManagement.deleteUser(${user.id})" title="删除用户">
              <i class="bi bi-trash"></i>
            </button>
          </div>
        </div>
      </div>
    `;
  }

  getStatusBadgeClass(status) {
    const classes = {
      'active': 'bg-success',
      'pending': 'bg-warning text-dark',
      'suspended': 'bg-secondary',
      'blocked': 'bg-danger'
    };
    return classes[status] || 'bg-secondary';
  }

  getStatusClass(status) {
    const classes = {
      'active': 'bg-success',
      'pending': 'bg-warning',
      'suspended': 'bg-secondary',
      'blocked': 'bg-danger'
    };
    return classes[status] || 'bg-secondary';
  }

  getStatusLabel(status) {
    const labels = {
      'active': '激活',
      'pending': '待审核',
      'suspended': '暂停',
      'blocked': '封禁'
    };
    return labels[status] || '未知';
  }

  // 新增：绑定状态判断方法
  isUserBound(user) {
    // 用户已绑定的条件：
    // 1. bind_status 是 'confirmed' 或 'bound'
    // 2. 或者 student_id 不为空
    return (user.bind_status === 'confirmed' || user.bind_status === 'bound') || user.student_id;
  }

  // 新增：获取绑定状态样式类
  getBindStatusClass(user) {
    return this.isUserBound(user) ? 'bg-success' : 'bg-warning';
  }

  // 新增：获取绑定状态标签
  getBindStatusLabel(user) {
    return this.isUserBound(user) ? '已绑定' : '未绑定';
  }

  renderRoleOptions() {
    // 渲染角色筛选选项
    const roleFilter = document.getElementById('roleFilter');
    roleFilter.innerHTML = '<option value="">所有角色</option>' +
      this.roles.map(role => `<option value="${role.name}">${role.name}</option>`).join('');
    
    // 渲染用户表单中的角色选项
    this.renderRoleCheckboxes('roleCheckboxGroup');
    this.renderRoleCheckboxes('batchRoleCheckboxGroup');
  }

  renderRoleCheckboxes(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;
    
    container.innerHTML = this.roles.map(role => `
      <div class="form-check">
        <input class="form-check-input" type="checkbox" value="${role.name}" id="${containerId}_${role.name}">
        <label class="form-check-label" for="${containerId}_${role.name}">
          ${role.name}
        </label>
      </div>
    `).join('');
  }

  updateFilterSummary() {
    const total = this.users.length;
    const filtered = this.filteredUsers.length;
    const selected = this.selectedUsers.size;
    
    document.getElementById('totalUsersCount').textContent = total;
    document.getElementById('filteredUsersCount').textContent = filtered;
    document.getElementById('selectedUsersCount').textContent = selected;
    
    // 更新批量操作按钮状态
    const hasSelection = selected > 0;
    document.getElementById('batchDeleteBtn').disabled = !hasSelection;
    document.getElementById('batchRoleBtn').disabled = !hasSelection;
    document.getElementById('batchStatusBtn').disabled = !hasSelection;
  }

  toggleSelectAll(checked) {
    const checkboxes = document.querySelectorAll('.user-checkbox');
    checkboxes.forEach(cb => {
      cb.checked = checked;
      const userId = parseInt(cb.value);
      if (checked) {
        this.selectedUsers.add(userId);
      } else {
        this.selectedUsers.delete(userId);
      }
    });
    this.updateCardSelection();
    this.updateFilterSummary();
  }

  updateSelectAllState() {
    const checkboxes = document.querySelectorAll('.user-checkbox');
    const selectAllCheckbox = document.getElementById('selectAllUsers');
    
    // 绑定单个复选框事件
    checkboxes.forEach(cb => {
      cb.addEventListener('change', (e) => {
        const userId = parseInt(e.target.value);
        if (e.target.checked) {
          this.selectedUsers.add(userId);
        } else {
          this.selectedUsers.delete(userId);
        }
        this.updateCardSelection();
        this.updateFilterSummary();
        
        // 更新全选状态
        const allChecked = Array.from(checkboxes).every(c => c.checked);
        const noneChecked = Array.from(checkboxes).every(c => !c.checked);
        selectAllCheckbox.checked = allChecked;
        selectAllCheckbox.indeterminate = !allChecked && !noneChecked;
      });
    });
    
    // 初始化全选状态
    const allChecked = Array.from(checkboxes).every(c => c.checked);
    const noneChecked = Array.from(checkboxes).every(c => !c.checked);
    selectAllCheckbox.checked = allChecked;
    selectAllCheckbox.indeterminate = !allChecked && !noneChecked;
  }

  updateCardSelection() {
    // 更新表格行选择状态
    document.querySelectorAll('.user-row').forEach(row => {
      const checkbox = row.querySelector('.user-checkbox');
      if (checkbox && checkbox.checked) {
        row.classList.add('table-primary');
      } else {
        row.classList.remove('table-primary');
      }
    });
    
    // 同时保持卡片选择状态（如果有卡片视图）
    document.querySelectorAll('.user-card').forEach(card => {
      const checkbox = card.querySelector('.user-checkbox');
      if (checkbox && checkbox.checked) {
        card.classList.add('selected');
      } else {
        card.classList.remove('selected');
      }
    });
  }

  changePage(page) {
    if (page < 1 || page > this.totalPages) return;
    this.currentPage = page;
    this.renderUsers();
    this.updatePagination();
  }

  changePageSize(size) {
    this.pageSize = size;
    this.currentPage = 1;
    this.updatePagination();
    this.renderUsers();
  }

  showLoadingState(show) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (show) {
      loadingOverlay.style.display = 'flex';
    } else {
      loadingOverlay.style.display = 'none';
    }
  }

  showMessage(message, type = 'info') {
    // 简单的消息提示实现
    const alertClass = {
      'success': 'alert-success',
      'error': 'alert-danger',
      'warning': 'alert-warning',
      'info': 'alert-info'
    }[type] || 'alert-info';
    
    const alertElement = document.createElement('div');
    alertElement.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    alertElement.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertElement.innerHTML = `
      ${message}
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertElement);
    
    // 自动移除
    setTimeout(() => {
      if (alertElement.parentNode) {
        alertElement.parentNode.removeChild(alertElement);
      }
    }, 5000);
  }

  async apiRequest(url, options = {}) {
    const token = localStorage.getItem('access_token');
    if (!token) {
      this.showMessage('请先登录', 'error');
      setTimeout(() => {
        window.location.href = '/auth/login';
      }, 2000);
      throw new Error('未找到访问令牌，请重新登录');
    }
    
    const defaultOptions = {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    };
    
    console.log(`API Request: ${options.method || 'GET'} ${url}`);
    
    try {
      const response = await fetch(url, { ...defaultOptions, ...options });
      console.log(`API Response status: ${response.status}`);
      
      if (!response.ok) {
        if (response.status === 401) {
          localStorage.removeItem('access_token'); // 清除无效token
          
          // 友好的过期提示
          this.showMessage('登录已过期，请重新登录', 'warning');
          
          // 显示确认对话框
          if (confirm('您的登录已过期，是否重新登录？')) {
            window.location.href = '/auth/login';
          } else {
            // 用户取消，仍然跳转到登录页面
            setTimeout(() => {
              window.location.href = '/auth/login';
            }, 3000);
          }
          
          throw new Error('Token已过期');
        }
        throw new Error(`HTTP错误: ${response.status}`);
      }
      
      const data = await response.json();
      console.log('API Response data:', data);
      return data;
    } catch (error) {
      console.error('API Request failed:', error);
      
      // 如果是Token过期错误，不再显示额外的错误消息
      if (error.message !== 'Token已过期') {
        this.showMessage(`请求失败: ${error.message}`, 'error');
      }
      throw error;
    }
  }

  // 用户操作方法
  showCreateUserModal() {
    document.getElementById('userFormTitle').textContent = '创建新用户';
    document.getElementById('userFormSubmitBtn').innerHTML = '<i class="bi bi-check2"></i> 创建';
    document.getElementById('editUserId').value = '';
    document.getElementById('userFormElement').reset();
    this.clearRoleSelections('roleCheckboxGroup');
    
    // 创建时密码为必填
    const passwordField = document.getElementById('password');
    const passwordRequired = document.getElementById('passwordRequired');
    passwordField.required = true;
    passwordField.placeholder = '请输入密码';
    if (passwordRequired) passwordRequired.style.display = 'inline';
    
    this.showModal('userFormModal');
  }

  async editUser(userId) {
    try {
      const response = await this.apiRequest(`/api/users/${userId}`);
      if (response.success) {
        const user = response.data;
        this.populateUserForm(user);
        document.getElementById('userFormTitle').textContent = '编辑用户';
        document.getElementById('userFormSubmitBtn').innerHTML = '<i class="bi bi-check2"></i> 保存';
        document.getElementById('editUserId').value = userId;
        
        // 编辑时密码非必填
        const passwordField = document.getElementById('password');
        const passwordRequired = document.getElementById('passwordRequired');
        passwordField.required = false;
        passwordField.placeholder = '编辑时留空表示不修改密码';
        if (passwordRequired) passwordRequired.style.display = 'none';
        
        this.showModal('userFormModal');
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      this.showMessage('获取用户信息失败', 'error');
    }
  }

  populateUserForm(user) {
    document.getElementById('username').value = user.username || '';
    document.getElementById('real_name').value = user.real_name || '';
    document.getElementById('mobile').value = user.mobile || '';
    document.getElementById('email').value = user.email || '';
    document.getElementById('user_type').value = user.user_type || 'web';
    document.getElementById('gender').value = user.gender || '';
    document.getElementById('department').value = user.department || '';
    document.getElementById('position').value = user.position || '';
    document.getElementById('status').value = user.status || 'active';
    document.getElementById('remark').value = user.remark || '';
    document.getElementById('password').value = '';
    
    // 设置角色选择
    this.clearRoleSelections('roleCheckboxGroup');
    if (user.roles) {
      user.roles.forEach(roleName => {
        const checkbox = document.getElementById(`roleCheckboxGroup_${roleName}`);
        if (checkbox) checkbox.checked = true;
      });
    }
  }

  clearRoleSelections(containerId) {
    const checkboxes = document.querySelectorAll(`#${containerId} input[type="checkbox"]`);
    checkboxes.forEach(cb => cb.checked = false);
  }

  async handleFormSubmit(e) {
    e.preventDefault();
    
    const userId = document.getElementById('editUserId').value;
    const isEdit = !!userId;
    
    const formData = {
      username: document.getElementById('username').value,
      real_name: document.getElementById('real_name').value,
      mobile: document.getElementById('mobile').value,
      email: document.getElementById('email').value,
      user_type: document.getElementById('user_type').value,
      gender: document.getElementById('gender').value,
      department: document.getElementById('department').value,
      position: document.getElementById('position').value,
      status: document.getElementById('status').value,
      remark: document.getElementById('remark').value,
      roles: Array.from(document.querySelectorAll('#roleCheckboxGroup input:checked')).map(cb => cb.value)
    };
    
    const password = document.getElementById('password').value;
    
    // 创建用户时密码为必填项
    if (!isEdit && !password) {
      this.showError('创建用户时密码为必填项');
      return;
    }
    
    if (password || !isEdit) {
      formData.password = password;
    }
    
    try {
      const url = isEdit ? `/api/users/edit/${userId}` : '/api/users/create';
      const method = isEdit ? 'PUT' : 'POST';
      
      const response = await this.apiRequest(url, {
        method,
        body: JSON.stringify(formData)
      });
      
      if (response.success) {
        this.showMessage(isEdit ? '用户更新成功' : '用户创建成功', 'success');
        this.hideUserFormModal();
        this.loadUsers();
      } else {
        throw new Error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('保存用户失败:', error);
      this.showMessage('保存用户失败: ' + error.message, 'error');
    }
  }

  async deleteUser(userId) {
    if (!confirm('确定要删除这个用户吗？此操作不可恢复。')) return;
    
    try {
      const response = await this.apiRequest(`/api/users/delete/${userId}`, {
        method: 'DELETE'
      });
      
      if (response.success) {
        this.showMessage('用户删除成功', 'success');
        this.selectedUsers.delete(userId);
        this.loadUsers();
      } else {
        throw new Error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      this.showMessage('删除用户失败: ' + error.message, 'error');
    }
  }

  viewUserLog(userId) {
    // TODO: 实现用户日志查看功能
    this.showMessage('用户日志功能待实现', 'info');
  }

  viewUserDetail(userId) {
    const user = this.users.find(u => u.id === userId);
    if (!user) {
      this.showMessage('用户不存在', 'error');
      return;
    }
    
    // 创建用户详情模态框
    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-person-circle me-2"></i>用户详情 - ${user.username}
            </h5>
            <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-md-6">
                <h6 class="text-muted mb-3">基本信息</h6>
                <table class="table table-sm">
                  <tr><td><strong>用户名:</strong></td><td>${user.username || '-'}</td></tr>
                  <tr><td><strong>真实姓名:</strong></td><td>${user.real_name || '-'}</td></tr>
                  <tr><td><strong>昵称:</strong></td><td>${user.nickname || '-'}</td></tr>
                  <tr><td><strong>性别:</strong></td><td>${user.gender || '-'}</td></tr>
                  <tr><td><strong>手机号:</strong></td><td>${user.mobile || '-'}</td></tr>
                  <tr><td><strong>邮箱:</strong></td><td>${user.email || '-'}</td></tr>
                  <tr><td><strong>地址:</strong></td><td>${user.address || '-'}</td></tr>
                </table>
              </div>
              <div class="col-md-6">
                <h6 class="text-muted mb-3">系统信息</h6>
                <table class="table table-sm">
                  <tr><td><strong>用户类型:</strong></td><td>${user.user_type === 'miniprogram' ? '小程序用户' : 'PC端用户'}</td></tr>
                  <tr><td><strong>状态:</strong></td><td><span class="badge ${this.getStatusBadgeClass(user.status)}">${this.getStatusLabel(user.status)}</span></td></tr>
                  <tr><td><strong>角色:</strong></td><td>${user.roles ? user.roles.join(', ') : '-'}</td></tr>
                  <tr><td><strong>部门:</strong></td><td>${user.department || '-'}</td></tr>
                  <tr><td><strong>职位:</strong></td><td>${user.position || '-'}</td></tr>
                  <tr><td><strong>注册时间:</strong></td><td>${user.created_at ? new Date(user.created_at).toLocaleString() : '-'}</td></tr>
                  <tr><td><strong>最后登录:</strong></td><td>${user.last_login ? new Date(user.last_login).toLocaleString() : '-'}</td></tr>
                </table>
              </div>
            </div>
            
            <div class="row mt-3">
              <div class="col-md-6">
                <h6 class="text-muted mb-3">绑定信息</h6>
                <table class="table table-sm">
                  <tr>
                    <td><strong>绑定学生:</strong></td>
                    <td>
                      <span class="badge ${this.getBindStatusClass(user)}">
                        ${this.getBindStatusLabel(user)}
                      </span>
                    </td>
                  </tr>
                  ${user.education_id ? `<tr><td><strong>教育ID:</strong></td><td>${user.education_id}</td></tr>` : ''}
                </table>
              </div>
              <div class="col-md-6">
                <h6 class="text-muted mb-3">微信绑定</h6>
                <table class="table table-sm">
                  <tr>
                    <td><strong>绑定微信:</strong></td>
                    <td>
                      <span class="badge ${user.wechat_bound ? 'bg-success' : 'bg-secondary'}">
                        ${user.wechat_bound ? '已绑定' : '未绑定'}
                      </span>
                    </td>
                  </tr>
                  ${user.wechat_id ? `<tr><td><strong>微信ID:</strong></td><td><small class="text-muted">${user.wechat_id}</small></td></tr>` : ''}
                </table>
              </div>
            </div>
            ${user.remark ? `
              <div class="mt-3">
                <h6 class="text-muted">备注</h6>
                <div class="alert alert-light">${user.remark}</div>
              </div>
            ` : ''}
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
            <button type="button" class="btn btn-primary" onclick="userManagement.editUser(${user.id}); this.closest('.modal').remove();">编辑用户</button>
          </div>
        </div>
      </div>
    `;
    
    document.body.appendChild(modal);
    document.body.classList.add('modal-open');
  }

  // 批量操作
  async batchDelete() {
    if (this.selectedUsers.size === 0) return;
    
    if (!confirm(`确定要删除选中的 ${this.selectedUsers.size} 个用户吗？此操作不可恢复。`)) return;
    
    try {
      const userIds = Array.from(this.selectedUsers);
      const response = await this.apiRequest('/api/users/batch_delete', {
        method: 'POST',
        body: JSON.stringify({ user_ids: userIds })
      });
      
      if (response.success) {
        this.showMessage('批量删除成功', 'success');
        this.selectedUsers.clear();
        this.loadUsers();
      } else {
        throw new Error(response.message || '批量删除失败');
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      this.showMessage('批量删除失败: ' + error.message, 'error');
    }
  }

  showBatchRoleModal() {
    if (this.selectedUsers.size === 0) return;
    
    document.getElementById('batchRoleUserCount').textContent = this.selectedUsers.size;
    this.clearRoleSelections('batchRoleCheckboxGroup');
    this.showModal('batchRoleModal');
  }

  async confirmBatchRoleAssignment() {
    const selectedRoles = Array.from(document.querySelectorAll('#batchRoleCheckboxGroup input:checked')).map(cb => cb.value);
    const userIds = Array.from(this.selectedUsers);
    
    if (selectedRoles.length === 0) {
      this.showMessage('请选择要分配的角色', 'warning');
      return;
    }
    
    try {
      const response = await this.apiRequest('/api/users/batch_assign_roles', {
        method: 'POST',
        body: JSON.stringify({
          user_ids: userIds,
          roles: selectedRoles
        })
      });
      
      if (response.success) {
        this.showMessage('批量角色分配成功', 'success');
        this.hideModal('batchRoleModal');
        this.loadUsers();
      } else {
        throw new Error(response.message || '批量角色分配失败');
      }
    } catch (error) {
      console.error('批量角色分配失败:', error);
      this.showMessage('批量角色分配失败: ' + error.message, 'error');
    }
  }

  showBatchStatusModal() {
    if (this.selectedUsers.size === 0) return;
    
    document.getElementById('batchStatusUserCount').textContent = this.selectedUsers.size;
    this.showModal('batchStatusModal');
  }

  async confirmBatchStatusChange() {
    const newStatus = document.getElementById('batchStatusSelect').value;
    const userIds = Array.from(this.selectedUsers);
    
    try {
      const response = await this.apiRequest('/api/users/batch_update_status', {
        method: 'POST',
        body: JSON.stringify({
          user_ids: userIds,
          status: newStatus
        })
      });
      
      if (response.success) {
        this.showMessage('批量状态变更成功', 'success');
        this.hideModal('batchStatusModal');
        this.loadUsers();
      } else {
        throw new Error(response.message || '批量状态变更失败');
      }
    } catch (error) {
      console.error('批量状态变更失败:', error);
      this.showMessage('批量状态变更失败: ' + error.message, 'error');
    }
  }

  // 模态框控制
  showModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.style.display = 'block';
    modal.classList.add('show');
    document.body.classList.add('modal-open');
  }

  hideModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.style.display = 'none';
    modal.classList.remove('show');
    document.body.classList.remove('modal-open');
  }

  hideUserFormModal() {
    this.hideModal('userFormModal');
  }
}

// 密码验证增强功能
class UserPasswordValidator {
  static bindPasswordValidation() {
    document.addEventListener('input', (e) => {
      if (e.target.type === 'password' && e.target.id.includes('password')) {
        UserPasswordValidator.validatePasswordField(e.target);
      }
    });
  }
  
  static validatePasswordField(passwordInput) {
    const password = passwordInput.value;
    const validation = UserPasswordValidator.validatePassword(password);
    
    // 查找或创建强度显示元素
    let strengthContainer = passwordInput.parentNode.nextElementSibling;
    if (!strengthContainer || !strengthContainer.classList.contains('password-strength-container')) {
      strengthContainer = document.createElement('div');
      strengthContainer.className = 'password-strength-container mt-2';
      passwordInput.parentNode.insertAdjacentElement('afterend', strengthContainer);
    }
    
    strengthContainer.innerHTML = `
      <div class="password-strength bg-${UserPasswordValidator.getStrengthColor(validation.strength)}" 
           style="height: 4px; width: ${(validation.strength / 4) * 100}%; border-radius: 2px; transition: all 0.3s ease;"></div>
      <div class="strength-text mt-1">
        <small class="text-${UserPasswordValidator.getStrengthColor(validation.strength)}">
          密码强度: ${UserPasswordValidator.getStrengthText(validation.strength)}
        </small>
        ${validation.messages.length > 0 ? 
          `<br><small class="text-warning">${validation.messages.join(', ')}</small>` : ''}
      </div>
    `;
  }
  
  static validatePassword(password) {
    const result = {
      isValid: false,
      strength: 0,
      messages: []
    };
    
    if (!password) {
      result.messages.push('密码不能为空');
      return result;
    }
    
    // 长度检查
    if (password.length < 6) {
      result.messages.push('密码长度至少6位');
    } else {
      result.strength += 1;
    }
    
    // 包含数字
    if (/\d/.test(password)) {
      result.strength += 1;
    } else {
      result.messages.push('密码应包含数字');
    }
    
    // 包含字母
    if (/[a-zA-Z]/.test(password)) {
      result.strength += 1;
    } else {
      result.messages.push('密码应包含字母');
    }
    
    // 包含特殊字符
    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
      result.strength += 1;
    } else if (password.length >= 8) {
      result.messages.push('建议包含特殊字符以增强安全性');
    }
    
    result.isValid = result.strength >= 2 && password.length >= 6;
    return result;
  }
  
  static getStrengthText(strength) {
    const texts = ['很弱', '弱', '中等', '强', '很强'];
    return texts[strength] || '很弱';
  }
  
  static getStrengthColor(strength) {
    const colors = ['danger', 'warning', 'info', 'success', 'success'];
    return colors[strength] || 'danger';
  }
}

// 初始化用户管理系统
let userManagement;
document.addEventListener('DOMContentLoaded', () => {
  userManagement = new UserManagement();
  
  // 绑定密码验证
  UserPasswordValidator.bindPasswordValidation();
  
  // 初始化用户导入器
  if (typeof UserImporter !== 'undefined') {
    window.userImporter = new UserImporter(userManagement);
  }
  
  console.log('Enhanced user management system with password validation and import features initialized');
});
